home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / mozilla-thunderbird / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2007-04-03  |  94.9 KB  |  2,916 lines

  1. //@line 41 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  10. const PREF_APP_UPDATE_URL                 = "app.update.url";
  11. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  12. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  13. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  14. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  15. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  16. const PREF_APP_EXTENSIONS_VERSION         = "app.extensions.version";
  17. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  18. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  19. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never.";
  20.  
  21. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  22. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  23. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  24. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  25. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  26.  
  27. const KEY_APPDIR          = "XCurProcD";
  28.  
  29. const DIR_UPDATES         = "updates";
  30. const FILE_UPDATE_STATUS  = "update.status";
  31. const FILE_UPDATE_ARCHIVE = "update.mar";
  32. const FILE_UPDATE_LOG     = "update.log"
  33. const FILE_UPDATES_DB     = "updates.xml";
  34. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  35. const FILE_PERMS_TEST     = "update.test";
  36. const FILE_LAST_LOG       = "last-update.log";
  37.  
  38. const MODE_RDONLY   = 0x01;
  39. const MODE_WRONLY   = 0x02;
  40. const MODE_CREATE   = 0x08;
  41. const MODE_APPEND   = 0x10;
  42. const MODE_TRUNCATE = 0x20;
  43.  
  44. const PERMS_FILE      = 0644;
  45. const PERMS_DIRECTORY = 0755;
  46.  
  47. const STATE_NONE            = null;
  48. const STATE_DOWNLOADING     = "downloading";
  49. const STATE_PENDING         = "pending";
  50. const STATE_APPLYING        = "applying";
  51. const STATE_SUCCEEDED       = "succeeded";
  52. const STATE_DOWNLOAD_FAILED = "download-failed";
  53. const STATE_FAILED          = "failed";
  54.  
  55. // From updater/errors.h:
  56. const WRITE_ERROR = 7;
  57.  
  58. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  59. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  60. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  61.  
  62. // Values for the PREF_APP_UPDATE_INCOMPATIBLE_MODE pref. See documentation in
  63. // code below. 
  64. const INCOMPATIBLE_MODE_NEWVERSIONS   = 0;
  65. const INCOMPATIBLE_MODE_NONEWVERSIONS = 1;
  66.  
  67. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  68.  
  69. const nsILocalFile            = Components.interfaces.nsILocalFile;
  70. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  71. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  72. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  73. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  74. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  75. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  76. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  77.  
  78. const Node = Components.interfaces.nsIDOMNode;
  79.  
  80. var gApp        = null;
  81. var gPref       = null;
  82. var gOS         = null;
  83. var gABI        = null;
  84. var gConsole    = null;
  85. var gLogEnabled = { };
  86.  
  87. // shared code for suppressing bad cert dialogs
  88. //@line 40 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/../../shared/src/badCertHandler.js"
  89.  
  90. /**
  91.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  92.  */
  93. function checkCert(channel) {
  94.   if (!channel.originalURI.schemeIs("https"))  // bypass
  95.     return;
  96.  
  97.   const Ci = Components.interfaces;  
  98.   var cert =
  99.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  100.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  101.  
  102.   var issuer = cert.issuer;
  103.   while (issuer && !cert.equals(issuer)) {
  104.     cert = issuer;
  105.     issuer = cert.issuer;
  106.   }
  107.  
  108.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  109.     throw "cert issuer is not built-in";
  110. }
  111.  
  112. /**
  113.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  114.  * security dialogs from being shown to the user.  It is better to simply fail
  115.  * if the certificate is bad. See bug 304286.
  116.  */
  117. function BadCertHandler() {
  118. }
  119. BadCertHandler.prototype = {
  120.  
  121.   // nsIBadCertListener
  122.   confirmUnknownIssuer: function(socketInfo, cert, certAddType) {
  123.     LOG("EM BadCertHandler: Unknown issuer");
  124.     return false;
  125.   },
  126.  
  127.   confirmMismatchDomain: function(socketInfo, targetURL, cert) {
  128.     LOG("EM BadCertHandler: Mismatched domain");
  129.     return false;
  130.   },
  131.  
  132.   confirmCertExpired: function(socketInfo, cert) {
  133.     LOG("EM BadCertHandler: Expired certificate");
  134.     return false;
  135.   },
  136.  
  137.   notifyCrlNextupdate: function(socketInfo, targetURL, cert) {
  138.   },
  139.  
  140.   // nsIChannelEventSink
  141.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  142.     // make sure the certificate of the old channel checks out before we follow
  143.     // a redirect from it.  See bug 340198.
  144.     checkCert(oldChannel);
  145.   },
  146.  
  147.   // nsIInterfaceRequestor
  148.   getInterface: function(iid) {
  149.     if (iid.equals(Components.interfaces.nsIBadCertListener) ||
  150.         iid.equals(Components.interfaces.nsIChannelEventSink))
  151.       return this;
  152.  
  153.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  154.     return null;
  155.   },
  156.  
  157.   // nsISupports
  158.   QueryInterface: function(iid) {
  159.     if (!iid.equals(Components.interfaces.nsIBadCertListener) &&
  160.         !iid.equals(Components.interfaces.nsIChannelEventSink) &&
  161.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  162.         !iid.equals(Components.interfaces.nsISupports))
  163.       throw Components.results.NS_ERROR_NO_INTERFACE;
  164.     return this;
  165.   }
  166. };
  167. //@line 128 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  168.  
  169. /**
  170.  * Logs a string to the error console. 
  171.  * @param   string
  172.  *          The string to write to the error console..
  173.  */  
  174. function LOG(module, string) {
  175.   if (module in gLogEnabled) {
  176.     dump("*** " + module + ":" + string + "\n");
  177.     gConsole.logStringMessage(string);
  178.   }
  179. }
  180.  
  181. /**
  182.  * Convert a string containing binary values to hex.
  183.  */
  184. function binaryToHex(input) {
  185.   var result = "";
  186.   for (var i = 0; i < input.length; ++i) {
  187.     var hex = input.charCodeAt(i).toString(16);
  188.     if (hex.length == 1)
  189.       hex = "0" + hex;
  190.     result += hex;
  191.   }
  192.   return result;
  193. }
  194.  
  195. /**
  196.  * Gets a File URL spec for a nsIFile
  197.  * @param   file
  198.  *          The file to get a file URL spec to
  199.  * @returns The file URL spec to the file
  200.  */
  201. function getURLSpecFromFile(file) {
  202.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  203.                          .getService(Components.interfaces.nsIIOService);
  204.   var fph = ioServ.getProtocolHandler("file")
  205.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  206.   return fph.getURLSpecFromFile(file);
  207. }
  208.  
  209. /**
  210.  * Gets the specified directory at the specified hierarchy under a 
  211.  * Directory Service key. 
  212.  * @param   key
  213.  *          The Directory Service Key to start from
  214.  * @param   pathArray
  215.  *          An array of path components to locate beneath the directory 
  216.  *          specified by |key|
  217.  * @return  nsIFile object for the location specified. If the directory
  218.  *          requested does not exist, it is created, along with any
  219.  *          parent directories that need to be created.
  220.  */
  221. function getDir(key, pathArray) {
  222.   return getDirInternal(key, pathArray, true);
  223. }
  224.  
  225. /**
  226.  * Gets the specified directory at the speciifed hierarchy under a 
  227.  * Directory Service key. 
  228.  * @param   key
  229.  *          The Directory Service Key to start from
  230.  * @param   pathArray
  231.  *          An array of path components to locate beneath the directory 
  232.  *          specified by |key|
  233.  * @return  nsIFile object for the location specified. If the directory
  234.  *          requested does not exist, it is NOT created.
  235.  */
  236. function getDirNoCreate(key, pathArray) {
  237.   return getDirInternal(key, pathArray, false);
  238. }
  239.  
  240. /**
  241.  * Gets the specified directory at the speciifed hierarchy under a 
  242.  * Directory Service key. 
  243.  * @param   key
  244.  *          The Directory Service Key to start from
  245.  * @param   pathArray
  246.  *          An array of path components to locate beneath the directory 
  247.  *          specified by |key|
  248.  * @param   shouldCreate
  249.  *          true if the directory hierarchy specified in |pathArray|
  250.  *          should be created if it does not exist,
  251.  *          false otherwise.
  252.  * @return  nsIFile object for the location specified. 
  253.  */
  254. function getDirInternal(key, pathArray, shouldCreate) {
  255.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  256.                               .getService(Components.interfaces.nsIProperties);
  257.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  258.   for (var i = 0; i < pathArray.length; ++i) {
  259.     dir.append(pathArray[i]);
  260.     if (shouldCreate && !dir.exists())
  261.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  262.   }
  263.   return dir;
  264. }
  265.  
  266. /**
  267.  * Gets the file at the speciifed hierarchy under a Directory Service key.
  268.  * @param   key
  269.  *          The Directory Service Key to start from
  270.  * @param   pathArray
  271.  *          An array of path components to locate beneath the directory 
  272.  *          specified by |key|. The last item in this array must be the
  273.  *          leaf name of a file.
  274.  * @return  nsIFile object for the file specified. The file is NOT created
  275.  *          if it does not exist, however all required directories along 
  276.  *          the way are.
  277.  */
  278. function getFile(key, pathArray) {
  279.   var file = getDir(key, pathArray.slice(0, -1));
  280.   file.append(pathArray[pathArray.length - 1]);
  281.   return file;
  282. }
  283.  
  284. /**
  285.  * Closes a Safe Output Stream
  286.  * @param   fos
  287.  *          The Safe Output Stream to close
  288.  */
  289. function closeSafeOutputStream(fos) {
  290.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  291.     try {
  292.       fos.finish();
  293.     }
  294.     catch (e) {
  295.       fos.close();
  296.     }
  297.   }
  298.   else
  299.     fos.close();
  300. }
  301.  
  302. /**
  303.  * Returns human readable status text from the updates.properties bundle
  304.  * based on an error code
  305.  * @param   code
  306.  *          The error code to look up human readable status text for
  307.  * @param   defaultCode
  308.  *          The default code to look up should human readable status text
  309.  *          not exist for |code|
  310.  * @returns A human readable status text string
  311.  */
  312. function getStatusTextFromCode(code, defaultCode) {
  313.   var sbs = 
  314.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  315.       getService(Components.interfaces.nsIStringBundleService);
  316.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  317.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  318.   try {
  319.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  320.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  321.   }
  322.   catch (e) {
  323.     // Use the default reason
  324.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  325.   }
  326.   return reason;
  327. }
  328.  
  329. /**
  330.  * Get the Active Updates directory
  331.  * @returns The active updates directory, as a nsIFile object
  332.  */
  333. function getUpdatesDir() {
  334.   // Right now, we only support downloading one patch at a time, so we always
  335.   // use the same target directory.
  336.   var fileLocator =
  337.       Components.classes["@mozilla.org/file/directory_service;1"].
  338.       getService(Components.interfaces.nsIProperties);
  339.   var appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  340.   appDir.append(DIR_UPDATES);
  341.   appDir.append("0");
  342.   if (!appDir.exists())
  343.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  344.   return appDir;
  345. }
  346.  
  347. /**
  348.  * Reads the update state from the update.status file in the specified
  349.  * directory.
  350.  * @param   dir
  351.  *          The dir to look for an update.status file in
  352.  * @returns The status value of the update.
  353.  */
  354. function readStatusFile(dir) {
  355.   var statusFile = dir.clone();
  356.   statusFile.append(FILE_UPDATE_STATUS);
  357.   LOG("General", "Reading Status File: " + statusFile.path);
  358.   return readStringFromFile(statusFile) || STATE_NONE;
  359. }
  360.  
  361. /**
  362.  * Writes the current update operation/state to a file in the patch 
  363.  * directory, indicating to the patching system that operations need
  364.  * to be performed.
  365.  * @param   dir
  366.  *          The patch directory where the update.status file should be 
  367.  *          written.
  368.  * @param   state
  369.  *          The state value to write.
  370.  */
  371. function writeStatusFile(dir, state) {
  372.   var statusFile = dir.clone();
  373.   statusFile.append(FILE_UPDATE_STATUS);
  374.   writeStringToFile(statusFile, state);
  375. }
  376.  
  377. /**
  378.  * Removes the Updates Directory
  379.  */
  380. function cleanUpUpdatesDir() {
  381.   // Bail out if we don't have appropriate permissions
  382.   var updateDir;
  383.   try {
  384.     updateDir = getUpdatesDir();
  385.   }
  386.   catch (e) {
  387.     return;
  388.   }
  389.         
  390.   var e = updateDir.directoryEntries;
  391.   while (e.hasMoreElements()) {
  392.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  393.     // Preserve the last update log file for debugging purposes
  394.     if (f.leafName == FILE_UPDATE_LOG) {
  395.       try {
  396.         var dir = f.parent.parent;
  397.         var logFile = dir.clone();
  398.         logFile.append(FILE_LAST_LOG);
  399.         if (logFile.exists())
  400.           logFile.remove(false);
  401.         f.copyTo(dir, FILE_LAST_LOG);
  402.       }
  403.       catch (e) {
  404.         LOG("General", "Failed to copy file: " + f.path);
  405.       }
  406.     }
  407.     // Now, recursively remove this file.  The recusive removal is really
  408.     // only needed on Mac OSX because this directory will contain a copy of
  409.     // updater.app, which is itself a directory.
  410.     try {
  411.       f.remove(true);
  412.     }
  413.     catch (e) {
  414.       LOG("General", "Failed to remove file: " + f.path);
  415.     }
  416.   }
  417.   try {
  418.     updateDir.remove(false);
  419.   } catch (e) {
  420.     LOG("General", "Failed to remove update directory: " + updateDir.path + 
  421.         " - This is almost always bad. Exception = " + e);
  422.     throw e;
  423.   }
  424. }
  425.  
  426. /**
  427.  * Clean up updates list and the updates directory.
  428.  */
  429. function cleanupActiveUpdate() {
  430.   // Move the update from the Active Update list into the Past Updates list.
  431.   var um = 
  432.       Components.classes["@mozilla.org/updates/update-manager;1"].
  433.       getService(Components.interfaces.nsIUpdateManager);
  434.   um.activeUpdate = null;
  435.   um.saveUpdates();
  436.  
  437.   // Now trash the updates directory, since we're done with it
  438.   cleanUpUpdatesDir();
  439. }
  440.  
  441. /**
  442.  * Gets a preference value, handling the case where there is no default.
  443.  * @param   func
  444.  *          The name of the preference function to call, on nsIPrefBranch
  445.  * @param   preference
  446.  *          The name of the preference
  447.  * @param   defaultValue
  448.  *          The default value to return in the event the preference has 
  449.  *          no setting
  450.  * @returns The value of the preference, or undefined if there was no
  451.  *          user or default value.
  452.  */
  453. function getPref(func, preference, defaultValue) {
  454.   try {
  455.     return gPref[func](preference);
  456.   }
  457.   catch (e) {
  458.   }
  459.   return defaultValue;
  460. }
  461.  
  462. /**
  463.  * Gets the current value of the locale.  It's possible for this preference to
  464.  * be localized, so we have to do a little extra work here.  Similar code
  465.  * exists in nsHttpHandler.cpp when building the UA string.
  466.  */
  467. function getLocale() {
  468.   try {
  469.     return gPref.getComplexValue(PREF_GENERAL_USERAGENT_LOCALE,
  470.                                  nsIPrefLocalizedString).data;
  471.   } catch (e) {}
  472.  
  473.   return gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  474. }
  475.  
  476. /**
  477.  * An enumeration of items in a JS array.
  478.  * @constructor
  479.  */
  480. function ArrayEnumerator(aItems) {
  481.   this._index = 0;
  482.   if (aItems) {
  483.     for (var i = 0; i < aItems.length; ++i) {
  484.       if (!aItems[i])
  485.         aItems.splice(i, 1);      
  486.     }
  487.   }
  488.   this._contents = aItems;
  489. }
  490.  
  491. ArrayEnumerator.prototype = {
  492.   _index: 0,
  493.   _contents: [],
  494.   
  495.   hasMoreElements: function() {
  496.     return this._index < this._contents.length;
  497.   },
  498.   
  499.   getNext: function() {
  500.     return this._contents[this._index++];      
  501.   }
  502. };
  503.  
  504. /**
  505.  * Trims a prefix from a string.
  506.  * @param   string
  507.  *          The source string
  508.  * @param   prefix
  509.  *          The prefix to remove.
  510.  * @returns The suffix (string - prefix)
  511.  */
  512. function stripPrefix(string, prefix) {
  513.   return string.substr(prefix.length);
  514. }
  515.  
  516. /**
  517.  * Writes a string of text to a file.  A newline will be appended to the data
  518.  * written to the file.  This function only works with ASCII text.
  519.  */
  520. function writeStringToFile(file, text) {
  521.   var fos =
  522.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  523.       createInstance(nsIFileOutputStream);
  524.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  525.   if (!file.exists()) 
  526.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  527.   fos.init(file, modeFlags, PERMS_FILE, 0);
  528.   text += "\n";
  529.   fos.write(text, text.length);    
  530.   closeSafeOutputStream(fos);
  531. }
  532.  
  533. /**
  534.  * Reads a string of text from a file.  A trailing newline will be removed
  535.  * before the result is returned.  This function only works with ASCII text.
  536.  */
  537. function readStringFromFile(file) {
  538.   var fis =
  539.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  540.       createInstance(nsIFileInputStream);
  541.   var modeFlags = MODE_RDONLY;
  542.   if (!file.exists())
  543.     return null;
  544.   fis.init(file, modeFlags, PERMS_FILE, 0);
  545.   var sis =
  546.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  547.       createInstance(Components.interfaces.nsIScriptableInputStream);
  548.   sis.init(fis);
  549.   var text = sis.read(sis.available());
  550.   sis.close();
  551.   if (text[text.length - 1] == "\n")
  552.     text = text.slice(0, -1);
  553.   return text;
  554. }
  555.  
  556. // Read the update channel from defaults only.  We do this to ensure that
  557. // the channel is tightly coupled with the application and does not apply
  558. // to other instances of the application that may use the same profile.
  559. function getUpdateChannel() {
  560.   try {
  561.     var defaults =
  562.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  563.         getDefaultBranch(null);
  564.  
  565.     return defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  566.   } catch (e) {
  567.     return "default";  // failover when pref not found
  568.   }
  569. }
  570.  
  571. /**
  572.  * Update Patch
  573.  * @param   patch
  574.  *          A <patch> element to initialize this object with
  575.  * @constructor
  576.  */
  577. function UpdatePatch(patch) {
  578.   this._properties = {};
  579.   for (var i = 0; i < patch.attributes.length; ++i) {
  580.     var attr = patch.attributes.item(i);
  581.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  582.     switch (attr.name) {
  583.     case "selected":
  584.       this.selected = attr.value == "true";
  585.       break;
  586.     default:
  587.       this[attr.name] = attr.value;
  588.       break;
  589.     };
  590.   }
  591. }
  592. UpdatePatch.prototype = {
  593.   /**
  594.    * See nsIUpdateService.idl
  595.    */
  596.   serialize: function(updates) {
  597.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  598.     patch.setAttribute("type", this.type);
  599.     patch.setAttribute("URL", this.URL);
  600.     patch.setAttribute("hashFunction", this.hashFunction);
  601.     patch.setAttribute("hashValue", this.hashValue);
  602.     patch.setAttribute("size", this.size);
  603.     patch.setAttribute("selected", this.selected);
  604.     patch.setAttribute("state", this.state);
  605.     
  606.     for (var p in this._properties) {
  607.       if (this._properties[p].present)
  608.         patch.setAttribute(p, this._properties[p].data);
  609.     }
  610.     
  611.     return patch; 
  612.   },
  613.   
  614.   /**
  615.    * A hash of custom properties
  616.    */
  617.   _properties: null,
  618.   
  619.   /**
  620.    * See nsIWritablePropertyBag.idl
  621.    */
  622.   setProperty: function(name, value) {
  623.     this._properties[name] = { data: value, present: true };
  624.   },
  625.   
  626.   /**
  627.    * See nsIWritablePropertyBag.idl
  628.    */
  629.   deleteProperty: function(name) {
  630.     if (name in this._properties)
  631.       this._properties[name].present = false;
  632.     else
  633.       throw Components.results.NS_ERROR_FAILURE;
  634.   },
  635.   
  636.   /**
  637.    * See nsIPropertyBag.idl
  638.    */
  639.   get enumerator() {
  640.     var properties = [];
  641.     for (var p in this._properties)
  642.       properties.push(this._properties[p].data);
  643.     return new ArrayEnumerator(properties);
  644.   },
  645.   
  646.   /**
  647.    * See nsIPropertyBag.idl
  648.    */
  649.   getProperty: function(name) {
  650.     if (name in this._properties &&
  651.         this._properties[name].present)
  652.       return this._properties[name].data;
  653.     throw Components.results.NS_ERROR_FAILURE;
  654.   },
  655.   
  656.   /**
  657.    * Returns whether or not the update.status file for this patch exists at the 
  658.    * appropriate location. 
  659.    */
  660.   get statusFileExists() {
  661.     var statusFile = getUpdatesDir();
  662.     statusFile.append(FILE_UPDATE_STATUS);
  663.     return statusFile.exists();
  664.   },
  665.   
  666.   /**
  667.    * See nsIUpdateService.idl
  668.    */
  669.   get state() {
  670.     if (!this.statusFileExists)
  671.       return STATE_NONE;
  672.     return this._properties.state;
  673.   },
  674.   set state(val) {
  675.     this._properties.state = val;
  676.   },
  677.   
  678.   /**
  679.    * See nsISupports.idl
  680.    */
  681.   QueryInterface: function(iid) {
  682.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  683.         !iid.equals(Components.interfaces.nsIPropertyBag) && 
  684.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) && 
  685.         !iid.equals(Components.interfaces.nsISupports))
  686.       throw Components.results.NS_ERROR_NO_INTERFACE;
  687.     return this;
  688.   }
  689. };
  690.  
  691. /**
  692.  * Update
  693.  * Implements nsIUpdate
  694.  * @param   update
  695.  *          An <update> element to initialize this object with
  696.  * @constructor
  697.  */
  698. function Update(update) {
  699.   this._properties = {};
  700.   this._patches = [];
  701.   this.installDate = 0;
  702.   this.isCompleteUpdate = false;
  703.  
  704.   // Null <update>, assume this is a message container and do no 
  705.   // further initialization
  706.   if (!update)
  707.     return;
  708.     
  709.   for (var i = 0; i < update.childNodes.length; ++i) {
  710.     var patchElement = update.childNodes.item(i);
  711.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  712.         patchElement.localName != "patch")
  713.       continue;
  714.  
  715.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  716.     this._patches.push(new UpdatePatch(patchElement));
  717.   }
  718.  
  719.   for (var i = 0; i < update.attributes.length; ++i) {
  720.     var attr = update.attributes.item(i);
  721.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  722.     if (attr.name == "installDate" && attr.value) 
  723.       this.installDate = parseInt(attr.value);
  724.     else if (attr.name == "isCompleteUpdate")
  725.       this.isCompleteUpdate = attr.value == "true";
  726.     else if (attr.name == "isSecurityUpdate")
  727.       this.isSecurityUpdate = attr.value == "true";
  728.     else if (attr.name == "detailsURL")
  729.       this._detailsURL = attr.value;
  730.     else
  731.       this[attr.name] = attr.value;
  732.   }
  733.   
  734.   // The Update Name is either the string provided by the <update> element, or
  735.   // the string: "<App Name> <Update App Version>"
  736.   var name = "";
  737.   if (update.hasAttribute("name"))
  738.     name = update.getAttribute("name");
  739.   else {
  740.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  741.                         .getService(Components.interfaces.nsIStringBundleService);
  742.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  743.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  744.     var appName = brandBundle.GetStringFromName("brandShortName");
  745.     name = updateBundle.formatStringFromName("updateName", 
  746.                                              [appName, this.version], 2);
  747.   }
  748.   this.name = name;
  749. }
  750. Update.prototype = {
  751.   /**
  752.    * See nsIUpdateService.idl
  753.    */
  754.   get patchCount() {
  755.     return this._patches.length;
  756.   },
  757.   
  758.   /**
  759.    * See nsIUpdateService.idl
  760.    */
  761.   getPatchAt: function(index) {
  762.     return this._patches[index];
  763.   },
  764.  
  765.   /**
  766.    * See nsIUpdateService.idl
  767.    * 
  768.    * We use a copy of the state cached on this object in |_state| only when 
  769.    * there is no selected patch, i.e. in the case when we could not load 
  770.    * |.activeUpdate| from the update manager for some reason but still have
  771.    * the update.status file to work with. 
  772.    */
  773.   _state: "",
  774.   set state(state) {
  775.     if (this.selectedPatch)
  776.       this.selectedPatch.state = state;
  777.     this._state = state;
  778.     return state;
  779.   },
  780.   get state() {
  781.     if (this.selectedPatch)
  782.       return this.selectedPatch.state;
  783.     return this._state;
  784.   },
  785.  
  786.   /**
  787.    * See nsIUpdateService.idl
  788.    */
  789.   errorCode: 0,
  790.     
  791.   /**
  792.    * See nsIUpdateService.idl
  793.    */
  794.   get selectedPatch() {
  795.     for (var i = 0; i < this.patchCount; ++i) {
  796.       if (this._patches[i].selected)
  797.         return this._patches[i];
  798.     }
  799.     return null;
  800.   },
  801.   
  802.   /**
  803.    * See nsIUpdateService.idl
  804.    */
  805.   get detailsURL() {
  806.     if (!this._detailsURL) {
  807.       try {
  808.         // Try using a default details URL supplied by the distribution
  809.         // if the update XML does not supply one.
  810.         return gPref.getComplexValue(PREF_APP_UPDATE_URL_DETAILS,
  811.                                      nsIPrefLocalizedString).data;
  812.       }
  813.       catch (e) {
  814.       }
  815.     }
  816.     return this._detailsURL || "";
  817.   },
  818.   
  819.   /**
  820.    * See nsIUpdateService.idl
  821.    */
  822.   serialize: function(updates) {
  823.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  824.     update.setAttribute("type", this.type);
  825.     update.setAttribute("name", this.name);
  826.     update.setAttribute("version", this.version);
  827.     update.setAttribute("extensionVersion", this.extensionVersion);
  828.     update.setAttribute("detailsURL", this.detailsURL);
  829.     update.setAttribute("licenseURL", this.licenseURL);
  830.     update.setAttribute("serviceURL", this.serviceURL);
  831.     // to properly support updates to the MOZILLA_1_8_BRANCH and trunk
  832.     // write out the channel.  see bug #368082 for more details
  833.     update.setAttribute("channel", getUpdateChannel());
  834.     update.setAttribute("installDate", this.installDate);
  835.     update.setAttribute("statusText", this.statusText);
  836.     update.setAttribute("buildID", this.buildID);
  837.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  838.     updates.documentElement.appendChild(update);
  839.     
  840.     for (var p in this._properties) {
  841.       if (this._properties[p].present)
  842.         update.setAttribute(p, this._properties[p].data);
  843.     }
  844.     
  845.     for (var i = 0; i < this.patchCount; ++i)
  846.       update.appendChild(this.getPatchAt(i).serialize(updates));
  847.     
  848.     return update;
  849.   },
  850.    
  851.   /**
  852.    * A hash of custom properties
  853.    */
  854.   _properties: null,
  855.   
  856.   /**
  857.    * See nsIWritablePropertyBag.idl
  858.    */
  859.   setProperty: function(name, value) {
  860.     this._properties[name] = { data: value, present: true };
  861.   },
  862.   
  863.   /**
  864.    * See nsIWritablePropertyBag.idl
  865.    */
  866.   deleteProperty: function(name) {
  867.     if (name in this._properties)
  868.       this._properties[name].present = false;
  869.     else
  870.       throw Components.results.NS_ERROR_FAILURE;
  871.   },
  872.   
  873.   /**
  874.    * See nsIPropertyBag.idl
  875.    */
  876.   get enumerator() {
  877.     var properties = [];
  878.     for (var p in this._properties)
  879.       properties.push(this._properties[p].data);
  880.     return new ArrayEnumerator(properties);
  881.   },
  882.   
  883.   /**
  884.    * See nsIPropertyBag.idl
  885.    */
  886.   getProperty: function(name) {
  887.     if (name in this._properties &&
  888.         this._properties[name].present)
  889.       return this._properties[name].data;
  890.     throw Components.results.NS_ERROR_FAILURE;
  891.   },
  892.   
  893.   /**
  894.    * See nsISupports.idl
  895.    */
  896.   QueryInterface: function(iid) {
  897.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  898.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  899.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  900.         !iid.equals(Components.interfaces.nsISupports))
  901.       throw Components.results.NS_ERROR_NO_INTERFACE;
  902.     return this;
  903.   }
  904. }; 
  905.  
  906. /**
  907.  * UpdateService
  908.  * A Service for managing the discovery and installation of software updates.
  909.  * @constructor
  910.  */
  911. function UpdateService() {
  912.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  913.                     .getService(Components.interfaces.nsIXULAppInfo)
  914.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  915.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  916.                     .getService(Components.interfaces.nsIPrefBranch2);
  917.   gOS   = Components.classes["@mozilla.org/observer-service;1"]
  918.                     .getService(Components.interfaces.nsIObserverService);
  919.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  920.                        .getService(Components.interfaces.nsIConsoleService);  
  921.  
  922.   // Not all builds have a known ABI
  923.   try {
  924.     gABI = gApp.XPCOMABI;
  925.   }
  926.   catch (e) {
  927.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  928.   }
  929.  
  930. //@line 899 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  931.  
  932.   // Start the update timer only after a profile has been selected so that the
  933.   // appropriate values for the update check are read from the user's profile.  
  934.   gOS.addObserver(this, "profile-after-change", false);
  935.  
  936.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid 
  937.   // shutdown leaks.
  938.   gOS.addObserver(this, "xpcom-shutdown", false);
  939. }
  940.  
  941. UpdateService.prototype = {
  942.   /**
  943.    * The downloader we are using to download updates. There is only ever one of
  944.    * these.
  945.    */
  946.   _downloader: null,
  947.  
  948.   /**
  949.    * Handle Observer Service notifications
  950.    * @param   subject
  951.    *          The subject of the notification
  952.    * @param   topic
  953.    *          The notification name
  954.    * @param   data
  955.    *          Additional data
  956.    */
  957.   observe: function(subject, topic, data) {
  958.     switch (topic) {
  959.     case "profile-after-change":
  960.       gOS.removeObserver(this, "profile-after-change");
  961.       this._start();
  962.       break;
  963.     case "xpcom-shutdown":
  964.       gOS.removeObserver(this, "xpcom-shutdown");
  965.       
  966.       // Release Services
  967.       gApp      = null;
  968.       gPref     = null;
  969.       gOS       = null;
  970.       gConsole  = null;
  971.       break;
  972.     }
  973.   },
  974.   
  975.   /**
  976.    * Start the Update Service
  977.    */
  978.   _start: function() {
  979.     // Start logging
  980.     this._initLoggingPrefs();
  981.     
  982.     // Clean up any extant updates
  983.     this._postUpdateProcessing();
  984.  
  985.     // Register a background update check timer
  986.     var tm = 
  987.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  988.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  989.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  990.     tm.registerTimer("background-update-timer", this, interval);
  991.  
  992.     // Resume fetching...
  993.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  994.                         .getService(Components.interfaces.nsIUpdateManager);
  995.     var activeUpdate = um.activeUpdate;
  996.     if (activeUpdate) {
  997.       var status = this.downloadUpdate(activeUpdate, true);
  998.       if (status == STATE_NONE)
  999.         cleanupActiveUpdate();
  1000.     }
  1001.   },
  1002.   
  1003.   /**
  1004.    * Perform post-processing on updates lingering in the updates directory
  1005.    * from a previous browser session - either report install failures (and
  1006.    * optionally attempt to fetch a different version if appropriate) or 
  1007.    * notify the user of install success.
  1008.    */
  1009.   _postUpdateProcessing: function() {
  1010.     // Detect installation failures and notify
  1011.     
  1012.     // Bail out if we don't have appropriate permissions
  1013.     if (!this.canUpdate)
  1014.       return;
  1015.       
  1016.     var status = readStatusFile(getUpdatesDir()); 
  1017.  
  1018.     // Make sure to cleanup after an update that failed for an unknown reason
  1019.     if (status == "null")
  1020.       status = null;
  1021.  
  1022.     if (status == STATE_DOWNLOADING) {
  1023.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  1024.     }
  1025.     else if (status != null) {
  1026.       // null status means the update.status file is not present, because either:
  1027.       // 1) no update was performed, and so there's no UI to show
  1028.       // 2) an update was attempted but failed during checking, transfer or 
  1029.       //    verification, and was cleaned up at that point, and UI notifying of
  1030.       //    that error was shown at that stage. 
  1031.       var um = 
  1032.           Components.classes["@mozilla.org/updates/update-manager;1"].
  1033.           getService(Components.interfaces.nsIUpdateManager);
  1034.       var prompter = 
  1035.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  1036.           createInstance(Components.interfaces.nsIUpdatePrompt);
  1037.  
  1038.       var shouldCleanup = true;
  1039.       var update = um.activeUpdate;
  1040.       if (!update) {
  1041.         if ((status == STATE_SUCCEEDED) && (um.updateCount >= 1))
  1042.           update = um.getUpdateAt(0);
  1043.         else
  1044.           update = new Update(null);
  1045.       }
  1046.       update.state = status;
  1047.       var sbs = 
  1048.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  1049.           getService(Components.interfaces.nsIStringBundleService);
  1050.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1051.       if (status == STATE_SUCCEEDED) {
  1052.         update.statusText = bundle.GetStringFromName("installSuccess");
  1053.         
  1054.         // Dig through the update history to find the patch that was just
  1055.         // installed and update its metadata.
  1056.         for (var i = 0; i < um.updateCount; ++i) {
  1057.           var umUpdate = um.getUpdateAt(i);
  1058.           if (umUpdate && umUpdate.version == update.version &&
  1059.                           umUpdate.buildID == update.buildID) {
  1060.             umUpdate.statusText = update.statusText;
  1061.             break;
  1062.           }
  1063.         }
  1064.  
  1065.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  1066.         prompter.showUpdateInstalled(update);
  1067.  
  1068.         // Perform platform-specific post-update processing.
  1069.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  1070.           Components.classes[POST_UPDATE_CONTRACTID].
  1071.               createInstance(Components.interfaces.nsIRunnable).run();
  1072.         }
  1073.         
  1074.         // Done with this update. Clean it up.
  1075.         cleanupActiveUpdate();
  1076.       }
  1077.       else {
  1078.         // If we hit an error, then the error code will be included in the
  1079.         // status string following a colon.  If we had an I/O error, then we
  1080.         // assume that the patch is not invalid, and we restage the patch so
  1081.         // that it can be attempted again the next time we restart.
  1082.         var ary = status.split(": ");
  1083.         update.state = ary[0];
  1084.         if (update.state == STATE_FAILED && ary[1]) {
  1085.           update.errorCode = ary[1];
  1086.           if (update.errorCode == WRITE_ERROR) {
  1087.             prompter.showUpdateError(update);
  1088.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1089.             return;
  1090.           }
  1091.         }
  1092.  
  1093.         // Something went wrong with the patch application process.
  1094.         cleanupActiveUpdate();
  1095.  
  1096.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1097.         var oldType = update.selectedPatch ? update.selectedPatch.type 
  1098.                                            : "complete";
  1099.         if (update.selectedPatch && oldType == "partial") {
  1100.           // Partial patch application failed, try downloading the complete
  1101.           // update in the background instead.
  1102.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " + 
  1103.               "failed, downloading Complete Patch and maybe showing UI");
  1104.           var status = this.downloadUpdate(update, true);
  1105.           if (status == STATE_NONE)
  1106.             cleanupActiveUpdate();
  1107.         }
  1108.         else {
  1109.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " + 
  1110.               "only patch failed. Showing error.");
  1111.         }
  1112.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1113.         update.setProperty("patchingFailed", oldType);
  1114.         prompter.showUpdateError(update);
  1115.       }
  1116.     }
  1117.     else {
  1118.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1119.     }
  1120.   },
  1121.  
  1122.   /**
  1123.    * Initialize Logging preferences, formatted like so:
  1124.    *  app.update.log.<moduleName> = <true|false>
  1125.    */
  1126.   _initLoggingPrefs: function() {
  1127.     try {
  1128.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1129.                         .getService(Components.interfaces.nsIPrefService);
  1130.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1131.       var modules = logBranch.getChildList("", { value: 0 });
  1132.  
  1133.       for (var i = 0; i < modules.length; ++i) {
  1134.         if (logBranch.prefHasUserValue(modules[i]))
  1135.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1136.       }
  1137.     }
  1138.     catch (e) {
  1139.     }
  1140.   },
  1141.   
  1142.   /**
  1143.    *
  1144.    */
  1145.   _needsToPromptForUpdate: function(updates) {
  1146.     // First, check for Extension incompatibilities. These trump any preference
  1147.     // settings.
  1148.     var em = Components.classes["@mozilla.org/extensions/manager;1"]
  1149.                        .getService(Components.interfaces.nsIExtensionManager);
  1150.     var incompatibleList = { };
  1151.     for (var i = 0; i < updates.length; ++i) {
  1152.       var count = {};
  1153.       em.getIncompatibleItemList(gApp.ID, updates[i].extensionVersion,
  1154.                                  nsIUpdateItem.TYPE_ADDON, false, count);
  1155.       if (count.value > 0)
  1156.         return true;
  1157.     }
  1158.  
  1159.     // Now, inspect user preferences.
  1160.     
  1161.     // No prompt necessary, silently update...
  1162.     return false;
  1163.   },
  1164.   
  1165.   /**
  1166.    * Notified when a timer fires
  1167.    * @param   timer
  1168.    *          The timer that fired
  1169.    */
  1170.   notify: function(timer) {
  1171.     // If a download is in progress, then do nothing.
  1172.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1173.       return;
  1174.  
  1175.     var self = this;
  1176.     var listener = {
  1177.       /**
  1178.        * See nsIUpdateService.idl
  1179.        */
  1180.       onProgress: function(request, position, totalSize) { 
  1181.       },
  1182.       
  1183.       /**
  1184.        * See nsIUpdateService.idl
  1185.        */
  1186.       onCheckComplete: function(request, updates, updateCount) {
  1187.         self._selectAndInstallUpdate(updates);
  1188.       },
  1189.  
  1190.       /**
  1191.        * See nsIUpdateService.idl
  1192.        */
  1193.       onError: function(request, update) { 
  1194.         LOG("Checker", "Error during background update: " + update.statusText);
  1195.       },
  1196.     }
  1197.     this.backgroundChecker.checkForUpdates(listener, false);
  1198.   },
  1199.   
  1200.   /**
  1201.    * Determine whether or not an update requires user confirmation before it
  1202.    * can be installed.
  1203.    * @param   update
  1204.    *          The update to be installed
  1205.    * @returns true if a prompt UI should be shown asking the user if they want
  1206.    *          to install the update, false if the update should just be 
  1207.    *          silently downloaded and installed.
  1208.    */
  1209.   _shouldPrompt: function(update) {
  1210.     // There are two possible outcomes here:
  1211.     // 1. download and install the update automatically
  1212.     // 2. alert the user about the presence of an update before doing anything
  1213.     //
  1214.     // The outcome we follow is determined as follows:
  1215.     // 
  1216.     // Note:  all Major updates require notification and confirmation
  1217.     // 
  1218.     // Update Type      Mode      Incompatible    Outcome
  1219.     // Major            0         Yes or No       Notify and Confirm
  1220.     // Major            1         No              Notify and Confirm
  1221.     // Major            1         Yes             Notify and Confirm
  1222.     // Major            2         Yes or No       Notify and Confirm
  1223.     // Minor            0         Yes or No       Auto Install
  1224.     // Minor            1         No              Auto Install
  1225.     // Minor            1         Yes             Notify and Confirm
  1226.     // Minor            2         No              Auto Install
  1227.     // Minor            2         Yes             Notify and Confirm
  1228.     //
  1229.     // In addition, if there is a license associated with an update, regardless
  1230.     // of type it must be agreed to. 
  1231.     //
  1232.     // If app.update.enabled is set to false, an update check is not performed
  1233.     // at all, and so none of the decision making above is entered into.
  1234.     //
  1235.     if (update.type == "major") {
  1236.       LOG("Checker", "_shouldPrompt: Prompting because it is a major update");
  1237.       return true;
  1238.     }
  1239.  
  1240.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1241.     try {
  1242.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1243.     }
  1244.     catch (e) {
  1245.       licenseAccepted = false;
  1246.     }
  1247.     
  1248.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1249.     if (!updateEnabled) {
  1250.       LOG("Checker", "_shouldPrompt: Not prompting because update is " + 
  1251.           "disabled");
  1252.       return false;
  1253.     }
  1254.     
  1255.     // User has turned off automatic download and install
  1256.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1257.     if (!autoEnabled) {
  1258.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1259.       return true;
  1260.     }
  1261.     
  1262.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1263.     case 1:
  1264.       // Mode 1 is do not prompt only if there are no incompatibilities
  1265.       // releases
  1266.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1267.       return !isCompatible(update);
  1268.     case 2:
  1269.       // Mode 2 is do not prompt only if there are no incompatibilities
  1270.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1271.       return !isCompatible(update);
  1272.     }
  1273.     // Mode 0 is do not prompt regardless of incompatibilities
  1274.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1275.         "ignore incompatibilities");
  1276.     return false;
  1277.   },
  1278.  
  1279.   /**
  1280.    * Determine if we have all the strings we need to show the major update UI
  1281.    */
  1282.   haveStringsForMajorUpdate: function() {
  1283.     var sbs = 
  1284.         Components.classes["@mozilla.org/intl/stringbundle;1"].
  1285.         getService(Components.interfaces.nsIStringBundleService);
  1286.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1287.     
  1288.     var stringNamesForMajorUpdate =
  1289.         ["introType_minor_app", "introType_major_app_and_version",
  1290.          "licenseContentNotFound", "updateMoreInfoContentNotFound",
  1291.          "licenseContentDownloading", "updateMoreInfoContentDownloading",
  1292.          "updatesfound_minor.title", "updatesfound_major.title",
  1293.          "downloadButton_minor", "downloadButton_major", "neverButton"];
  1294.  
  1295.     try {
  1296.       for (var i = 0; i < stringNamesForMajorUpdate.length; ++i) {
  1297.         if (!updateBundle.GetStringFromName(stringNamesForMajorUpdate[i]))
  1298.           return false;
  1299.       }
  1300.       return true;
  1301.     }
  1302.     catch (ex) {
  1303.       LOG("Checker", "haveStringsForMajorUpdate: missing a string: " + ex);
  1304.       return false;
  1305.     }
  1306.   },
  1307.  
  1308.   /**
  1309.    * Determine which of the specified updates should be installed.
  1310.    * @param   updates
  1311.    *          An array of available updates
  1312.    */
  1313.   selectUpdate: function(updates) {
  1314.     if (updates.length == 0)
  1315.       return null;
  1316.     
  1317.     // Choose the newest of the available minor and major updates. 
  1318.     var majorUpdate = null, minorUpdate = null;
  1319.     var newestMinor = updates[0], newestMajor = updates[0];
  1320.  
  1321.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1322.                        .getService(Components.interfaces.nsIVersionComparator);
  1323.     for (var i = 0; i < updates.length; ++i) {
  1324.       if (updates[i].type == "major" && 
  1325.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1326.         majorUpdate = newestMajor = updates[i];
  1327.       if (updates[i].type == "minor" && 
  1328.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1329.         minorUpdate = newestMinor = updates[i];
  1330.     }
  1331.  
  1332.     // XXX sspitzer hack for the MOZILLA_1_8_0_BRANCH
  1333.     if (majorUpdate && !this.haveStringsForMajorUpdate()) {
  1334.       LOG("Checker", "selectUpdate:  have a major update, but can't offer it because we are missing strings");
  1335.       majorUpdate = null;
  1336.     }
  1337.  
  1338.     // IMPORTANT
  1339.     // If there's a minor update, always try and fetch that one first, 
  1340.     // otherwise use the newest major update.
  1341.     // selectUpdate() only returns one update.
  1342.     // if major were to trump minor, and we said "never" to the major
  1343.     // we'd never get the minor update, since selectUpdate()
  1344.     // would return the major update that the user said "never" to
  1345.     // (shadowing the important minor update with security fixes)
  1346.     return minorUpdate || majorUpdate;
  1347.   },
  1348.   
  1349.   /**
  1350.    * Determine which of the specified updates should be installed and
  1351.    * begin the download/installation process, optionally prompting the
  1352.    * user for permission if required.
  1353.    * @param   updates
  1354.    *          An array of available updates
  1355.    */
  1356.   _selectAndInstallUpdate: function(updates) {
  1357.     // Don't prompt if there's an active update - the user is already 
  1358.     // aware and is downloading, or performed some user action to prevent
  1359.     // notification.
  1360.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1361.                        .getService(Components.interfaces.nsIUpdateManager);
  1362.     if (um.activeUpdate)
  1363.       return;
  1364.     
  1365.     var update = this.selectUpdate(updates, updates.length);
  1366.     if (!update)
  1367.       return;
  1368.     
  1369.     // check if the user said "never" to this version
  1370.     // this check is done here, and not in selectUpdate() so that
  1371.     // the user can get an upgrade they said "never" to if they
  1372.     // manually do "Check for Updates..."
  1373.     // note, selectUpdate() only returns one update.
  1374.     // but in selectUpdate(), minor updates trump major updates
  1375.     // if major trumps minor, and we said "never" to the major
  1376.     // we'd never see the minor update.
  1377.     // 
  1378.     // note, the never decision should only apply to major updates
  1379.     // see bug #350636 for a scenario where this could potentially
  1380.     // be an issue
  1381.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH + update.version;
  1382.     var never = getPref("getBoolPref", neverPrefName, false);
  1383.     if (never && update.type == "major")
  1384.       return;
  1385.  
  1386.     if (this._shouldPrompt(update))
  1387.       showPromptIfNoIncompatibilities(update);
  1388.     else {
  1389.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1390.       var status = this.downloadUpdate(update, true);
  1391.       if (status == STATE_NONE)
  1392.         cleanupActiveUpdate();
  1393.     }
  1394.   },
  1395.  
  1396.   /**
  1397.    * The Checker used for background update checks.
  1398.    */
  1399.   _backgroundChecker: null,
  1400.   
  1401.   /**
  1402.    * See nsIUpdateService.idl
  1403.    */
  1404.   get backgroundChecker() {
  1405.     if (!this._backgroundChecker) 
  1406.       this._backgroundChecker = new Checker();
  1407.     return this._backgroundChecker;
  1408.   },
  1409.   
  1410.   /**
  1411.    * See nsIUpdateService.idl
  1412.    */
  1413.   get canUpdate() {
  1414.     try {
  1415.       var appDirFile = getFile(KEY_APPDIR, [FILE_PERMS_TEST]);
  1416.       if (!appDirFile.exists()) {
  1417.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1418.         appDirFile.remove(false);
  1419.       }
  1420.       var updateDir = getUpdatesDir();
  1421.       var upDirFile = updateDir.clone();
  1422.       upDirFile.append(FILE_PERMS_TEST);
  1423.       if (!upDirFile.exists()) {
  1424.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1425.         upDirFile.remove(false);
  1426.       }
  1427.     }
  1428.     catch (e) {
  1429.       // No write privileges to install directory
  1430.       return false;
  1431.     }
  1432.     // If the administrator has locked the app update functionality 
  1433.     // OFF - this is not just a user setting, so disable the manual
  1434.     // UI too.
  1435.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1436.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED))
  1437.       return false;
  1438.  
  1439.     // If we don't know the binary platform we're updating, we can't update.
  1440.     if (!gABI)
  1441.       return false;
  1442.  
  1443.     return true;
  1444.   },
  1445.   
  1446.   /**
  1447.    * See nsIUpdateService.idl
  1448.    */
  1449.   addDownloadListener: function(listener) {
  1450.     if (!this._downloader) {
  1451.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1452.       return;
  1453.     }
  1454.     this._downloader.addDownloadListener(listener);
  1455.   },
  1456.   
  1457.   /**
  1458.    * See nsIUpdateService.idl
  1459.    */
  1460.   removeDownloadListener: function(listener) {
  1461.     if (!this._downloader) {
  1462.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1463.       return;
  1464.     }
  1465.     this._downloader.removeDownloadListener(listener);
  1466.   },
  1467.   
  1468.   /**
  1469.    * See nsIUpdateService.idl
  1470.    */
  1471.   downloadUpdate: function(update, background) {
  1472.     if (!update)
  1473.       throw Components.results.NS_ERROR_NULL_POINTER;
  1474.     if (this.isDownloading) {
  1475.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1476.           background == this._downloader.background) {
  1477.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1478.         return readStatusFile(getUpdatesDir());
  1479.       }
  1480.       this._downloader.cancel();
  1481.     }
  1482.     this._downloader = new Downloader(background);
  1483.     return this._downloader.downloadUpdate(update);
  1484.   },
  1485.   
  1486.   /**
  1487.    * See nsIUpdateService.idl
  1488.    */
  1489.   pauseDownload: function() {
  1490.     if (this.isDownloading)
  1491.       this._downloader.cancel();
  1492.   },
  1493.   
  1494.   /**
  1495.    * See nsIUpdateService.idl
  1496.    */
  1497.   get isDownloading() {
  1498.     return this._downloader && this._downloader.isBusy;
  1499.   },
  1500.   
  1501.   /**
  1502.    * See nsISupports.idl
  1503.    */
  1504.   QueryInterface: function(iid) {
  1505.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1506.         !iid.equals(Components.interfaces.nsITimerCallback) && 
  1507.         !iid.equals(Components.interfaces.nsIObserver) && 
  1508.         !iid.equals(Components.interfaces.nsISupports))
  1509.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1510.     return this;
  1511.   }
  1512. };
  1513.  
  1514. /**
  1515.  * A service to manage active and past updates.
  1516.  * @constructor
  1517.  */
  1518. function UpdateManager() {
  1519.   // Ensure the Active Update file is loaded
  1520.   var updates = this._loadXMLFileIntoArray(getFile(KEY_APPDIR, 
  1521.     [FILE_UPDATE_ACTIVE]));
  1522.   if (updates.length > 0)
  1523.     this._activeUpdate = updates[0];
  1524. }
  1525. UpdateManager.prototype = {
  1526.   /**
  1527.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1528.    * objects.
  1529.    */
  1530.   _updates: null,
  1531.   
  1532.   /**
  1533.    * The current actively downloading/installing update, as a nsIUpdate object.
  1534.    */
  1535.   _activeUpdate: null,
  1536.   
  1537.   /**
  1538.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1539.    * @param   file
  1540.    *          A nsIFile for the updates.xml file
  1541.    * @returns The array of nsIUpdate items held in the file.
  1542.    */
  1543.   _loadXMLFileIntoArray: function(file) {
  1544.     if (!file.exists()) {
  1545.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1546.       return [];
  1547.     }
  1548.  
  1549.     var result = [];
  1550.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1551.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1552.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1553.     try {
  1554.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1555.                             .createInstance(Components.interfaces.nsIDOMParser);
  1556.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1557.       
  1558.       var updateCount = doc.documentElement.childNodes.length;
  1559.       for (var i = 0; i < updateCount; ++i) {
  1560.         var updateElement = doc.documentElement.childNodes.item(i);
  1561.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1562.             updateElement.localName != "update")
  1563.           continue;
  1564.  
  1565.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1566.         result.push(new Update(updateElement));
  1567.       }
  1568.     }
  1569.     catch (e) {
  1570.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " + 
  1571.           e);
  1572.     }
  1573.     fileStream.close();
  1574.     return result;
  1575.   },
  1576.   
  1577.   /**
  1578.    * Load the update manager, initializing state from state files.
  1579.    */
  1580.   _ensureUpdates: function() {
  1581.     if (!this._updates) {
  1582.       this._updates = this._loadXMLFileIntoArray(getFile(KEY_APPDIR, 
  1583.                         [FILE_UPDATES_DB]));
  1584.  
  1585.       // Make sure that any active update is part of our updates list
  1586.       var active = this.activeUpdate;
  1587.       if (active)
  1588.         this._addUpdate(active);
  1589.     }
  1590.   },
  1591.  
  1592.   /**
  1593.    * See nsIUpdateService.idl
  1594.    */
  1595.   getUpdateAt: function(index) {
  1596.     this._ensureUpdates();
  1597.     return this._updates[index];
  1598.   },
  1599.   
  1600.   /**
  1601.    * See nsIUpdateService.idl
  1602.    */
  1603.   get updateCount() {
  1604.     this._ensureUpdates();
  1605.     return this._updates.length;
  1606.   },
  1607.   
  1608.   /**
  1609.    * See nsIUpdateService.idl
  1610.    */
  1611.   get activeUpdate() {
  1612.     if (this._activeUpdate &&
  1613.         this._activeUpdate.serviceURL != Checker.prototype.updateURL) {
  1614.       // User switched channels, clear out any old active updates and remove
  1615.       // partial downloads
  1616.       this._activeUpdate = null;
  1617.       
  1618.       // Destroy the updates directory, since we're done with it.
  1619.       cleanUpUpdatesDir();
  1620.     }
  1621.     return this._activeUpdate;
  1622.   },
  1623.   set activeUpdate(activeUpdate) {
  1624.     this._addUpdate(activeUpdate);
  1625.     this._activeUpdate = activeUpdate;
  1626.     if (!activeUpdate) {
  1627.       // If |activeUpdate| is null, we have updated both lists - the active list
  1628.       // and the history list, so we want to write both files.
  1629.       this.saveUpdates();
  1630.     }
  1631.     else
  1632.       this._writeUpdatesToXMLFile([this._activeUpdate], 
  1633.                                   getFile(KEY_APPDIR, [FILE_UPDATE_ACTIVE]));
  1634.     return activeUpdate;
  1635.   },
  1636.   
  1637.   /**
  1638.    * Add an update to the Updates list. If the item already exists in the list,
  1639.    * replace the existing value with the new value.
  1640.    * @param   update
  1641.    *          The nsIUpdate object to add.
  1642.    */
  1643.   _addUpdate: function(update) {
  1644.     if (!update)
  1645.       return;
  1646.     if (this._updates) {
  1647.       for (var i = 0; i < this._updates.length; ++i) {
  1648.         if (this._updates[i].version == update.version &&
  1649.             this._updates[i].buildID == update.buildID) {
  1650.           // Replace the existing entry with the new value, updating
  1651.           // all metadata.
  1652.           this._updates[i] = update;
  1653.           return;
  1654.         }
  1655.       }
  1656.     }
  1657.     // Otherwise add it to the front of the list.
  1658.     if (update) 
  1659.       this._updates = [update].concat(this._updates);
  1660.   },
  1661.   
  1662.   /**
  1663.    * Serializes an array of updates to an XML file
  1664.    * @param   updates
  1665.    *          An array of nsIUpdate objects
  1666.    * @param   file
  1667.    *          The nsIFile object to serialize to
  1668.    */
  1669.   _writeUpdatesToXMLFile: function(updates, file) {
  1670.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1671.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1672.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1673.     if (!file.exists()) 
  1674.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1675.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1676.     
  1677.     try {
  1678.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1679.                             .createInstance(Components.interfaces.nsIDOMParser);
  1680.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1681.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1682.  
  1683.       for (var i = 0; i < updates.length; ++i) {
  1684.         if (updates[i])
  1685.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1686.       }
  1687.  
  1688.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1689.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1690.       serializer.serializeToStream(doc.documentElement, fos, null);
  1691.     }
  1692.     catch (e) {
  1693.     }
  1694.     
  1695.     closeSafeOutputStream(fos);
  1696.   },
  1697.  
  1698.   /**
  1699.    * See nsIUpdateService.idl
  1700.    */
  1701.   saveUpdates: function() {
  1702.     this._writeUpdatesToXMLFile([this._activeUpdate], 
  1703.                                 getFile(KEY_APPDIR, [FILE_UPDATE_ACTIVE]));
  1704.     if (this._updates) {
  1705.       this._writeUpdatesToXMLFile(this._updates, 
  1706.                                   getFile(KEY_APPDIR, [FILE_UPDATES_DB]));
  1707.     }
  1708.   },
  1709.   
  1710.   /**
  1711.    * See nsISupports.idl
  1712.    */
  1713.   QueryInterface: function(iid) {
  1714.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1715.         !iid.equals(Components.interfaces.nsISupports))
  1716.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1717.     return this;
  1718.   }
  1719. };
  1720.  
  1721.  
  1722. /**
  1723.  * Checker
  1724.  * Checks for new Updates
  1725.  * @constructor
  1726.  */
  1727. function Checker() {
  1728. }
  1729. Checker.prototype = {
  1730.   /**
  1731.    * The XMLHttpRequest object that performs the connection.
  1732.    */
  1733.   _request  : null,
  1734.   
  1735.   /**
  1736.    * The nsIUpdateCheckListener callback
  1737.    */
  1738.   _callback : null,
  1739.   
  1740.   /**
  1741.    * The URL of the update service XML file to connect to that contains details
  1742.    * about available updates.
  1743.    */
  1744.   get updateURL() {
  1745.     var defaults =
  1746.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1747.         getDefaultBranch(null);
  1748.  
  1749.     // Use the override URL if specified.
  1750.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1751.  
  1752.     // Otherwise, construct the update URL from component parts.
  1753.     if (!url) {
  1754.       try {
  1755.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1756.       } catch (e) {
  1757.       }
  1758.     }
  1759.  
  1760.     if (!url || url == "") {
  1761.       LOG("Checker", "Update URL not defined");
  1762.       return null;
  1763.     }
  1764.  
  1765.     url = url.replace(/%PRODUCT%/g, gApp.name);
  1766.     url = url.replace(/%VERSION%/g, gApp.version);
  1767.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  1768.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  1769.     url = url.replace(/%LOCALE%/g, getLocale());
  1770.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  1771.     url = url.replace(/\+/g, "%2B");
  1772.  
  1773.     LOG("Checker", "update url: " + url);
  1774.     return url;
  1775.   },
  1776.   
  1777.   /**
  1778.    * See nsIUpdateService.idl
  1779.    */
  1780.   checkForUpdates: function(listener, force) {
  1781.     if (!listener)
  1782.       throw Components.results.NS_ERROR_NULL_POINTER;
  1783.       
  1784.     if (!this.updateURL || (!this.enabled && !force))
  1785.       return;
  1786.       
  1787.     this._request = 
  1788.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  1789.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  1790.     this._request.open("GET", this.updateURL, true);
  1791.     this._request.channel.notificationCallbacks = new BadCertHandler();
  1792.     this._request.overrideMimeType("text/xml");
  1793.     this._request.setRequestHeader("Cache-Control", "no-cache");
  1794.     
  1795.     var self = this;
  1796.     this._request.onerror     = function(event) { self.onError(event);    };
  1797.     this._request.onload      = function(event) { self.onLoad(event);     };
  1798.     this._request.onprogress  = function(event) { self.onProgress(event); };
  1799.  
  1800.     LOG("Checker", "checkForUpdates: sending request to " + this.updateURL);
  1801.     this._request.send(null);
  1802.     
  1803.     this._callback = listener;
  1804.   },
  1805.   
  1806.   /**
  1807.    * When progress associated with the XMLHttpRequest is received.
  1808.    * @param   event
  1809.    *          The nsIDOMLSProgressEvent for the load.
  1810.    */
  1811.   onProgress: function(event) {
  1812.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  1813.     this._callback.onProgress(event.target, event.position, event.totalSize);
  1814.   },
  1815.   
  1816.   /**
  1817.    * Returns an array of nsIUpdate objects discovered by the update check.
  1818.    */
  1819.   get _updates() {
  1820.     var updatesElement = this._request.responseXML.documentElement;
  1821.     if (!updatesElement) {
  1822.       LOG("Checker", "get_updates: empty updates document?!");
  1823.       return [];
  1824.     }
  1825.  
  1826.     if (updatesElement.nodeName != "updates") {
  1827.       LOG("Checker", "get_updates: unexpected node name!");
  1828.       throw "";
  1829.     }
  1830.     
  1831.     var updates = [];
  1832.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  1833.       var updateElement = updatesElement.childNodes.item(i);
  1834.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1835.           updateElement.localName != "update")
  1836.         continue;
  1837.  
  1838.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1839.       var update = new Update(updateElement);
  1840.       update.serviceURL = this.updateURL;
  1841.       updates.push(update);
  1842.     }
  1843.  
  1844.     return updates;
  1845.   },
  1846.   
  1847.   /**
  1848.    * The XMLHttpRequest succeeded and the document was loaded.
  1849.    * @param   event
  1850.    *          The nsIDOMLSEvent for the load
  1851.    */
  1852.   onLoad: function(event) {
  1853.     LOG("Checker", "onLoad: request completed downloading document");
  1854.     
  1855.     try {
  1856.       checkCert(this._request.channel);
  1857.  
  1858.       // Analyze the resulting DOM and determine the set of updates to install
  1859.       var updates = this._updates;
  1860.       
  1861.       LOG("Checker", "Updates available: " + updates.length);
  1862.       
  1863.       // ... and tell the Update Service about what we discovered.
  1864.       this._callback.onCheckComplete(event.target, updates, updates.length);
  1865.     }
  1866.     catch (e) {
  1867.       LOG("Checker", "There was a problem with the update service URL specified, " + 
  1868.           "either the XML file was malformed or it does not exist at the location " + 
  1869.           "specified. Exception: " + e);
  1870.       var update = new Update(null);
  1871.       update.statusText = getStatusTextFromCode(404, 404);
  1872.       this._callback.onError(event.target, update);
  1873.     }
  1874.   },
  1875.   
  1876.   /**
  1877.    * There was an error of some kind during the XMLHttpRequest
  1878.    * @param   event
  1879.    *          The nsIDOMLSEvent for the load
  1880.    */
  1881.   onError: function(event) {
  1882.     LOG("Checker", "onError: error during load");
  1883.     
  1884.     var request = event.target;
  1885.     try {
  1886.       var status = request.status;
  1887.     }
  1888.     catch (e) {
  1889.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  1890.       status = req.status;
  1891.     }
  1892.     
  1893.     // If we can't find an error string specific to this status code, 
  1894.     // just use the 200 message from above, which means everything 
  1895.     // "looks" fine but there was probably an XML error or a bogus file.
  1896.     var update = new Update(null);
  1897.     update.statusText = getStatusTextFromCode(status, 200);
  1898.     this._callback.onError(request, update);
  1899.   },
  1900.   
  1901.   /**
  1902.    * Whether or not we are allowed to do update checking.
  1903.    */
  1904.   _enabled: true,
  1905.   
  1906.   /**
  1907.    * See nsIUpdateService.idl
  1908.    */
  1909.   get enabled() {
  1910.     var aus = 
  1911.         Components.classes["@mozilla.org/updates/update-service;1"].
  1912.         getService(Components.interfaces.nsIApplicationUpdateService);
  1913.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) && 
  1914.                   aus.canUpdate && this._enabled;
  1915.     return enabled;
  1916.   },
  1917.   
  1918.   /**
  1919.    * See nsIUpdateService.idl
  1920.    */
  1921.   stopChecking: function(duration) {
  1922.     // Always stop the current check
  1923.     if (this._request)
  1924.       this._request.abort();
  1925.     
  1926.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  1927.     switch (duration) {
  1928.     case nsIUpdateChecker.CURRENT_SESSION:
  1929.       this._enabled = false;
  1930.       break;
  1931.     case nsIUpdateChecker.ANY_CHECKS:
  1932.       this._enabled = false;
  1933.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  1934.       break;
  1935.     }
  1936.   },
  1937.   
  1938.   /**
  1939.    * See nsISupports.idl
  1940.    */
  1941.   QueryInterface: function(iid) {
  1942.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  1943.         !iid.equals(Components.interfaces.nsISupports))
  1944.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1945.     return this;
  1946.   }
  1947. };
  1948.  
  1949. /**
  1950.  * Manages the download of updates
  1951.  * @param   background
  1952.  *          Whether or not this downloader is operating in background
  1953.  *          update mode. 
  1954.  * @constructor
  1955.  */
  1956. function Downloader(background) {
  1957.   this.background = background;
  1958. }
  1959. Downloader.prototype = {
  1960.   /**
  1961.    * The nsIUpdatePatch that we are downloading
  1962.    */
  1963.   _patch: null,
  1964.   
  1965.   /**
  1966.    * The nsIUpdate that we are downloading
  1967.    */
  1968.   _update: null,
  1969.   
  1970.   /**
  1971.    * The nsIIncrementalDownload object handling the download
  1972.    */
  1973.   _request: null,
  1974.  
  1975.   /**
  1976.    * Whether or not the update being downloaded is a complete replacement of
  1977.    * the user's existing installation or a patch representing the difference
  1978.    * between the new version and the previous version.
  1979.    */
  1980.   isCompleteUpdate: null,
  1981.  
  1982.   /**
  1983.    * Cancels the active download.
  1984.    */  
  1985.   cancel: function() {
  1986.     if (this._request && 
  1987.         this._request instanceof Components.interfaces.nsIRequest) {
  1988.       const NS_BINDING_ABORTED = 0x804b0002;
  1989.       this._request.cancel(NS_BINDING_ABORTED);
  1990.     }
  1991.   },
  1992.  
  1993.   /**
  1994.    * Whether or not a patch has been downloaded and staged for installation.
  1995.    */
  1996.   get patchIsStaged() {
  1997.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  1998.   },
  1999.  
  2000.   /**
  2001.    * Verify the downloaded file.  We assume that the download is complete at
  2002.    * this point.
  2003.    */
  2004.   _verifyDownload: function() {
  2005.     if (!this._request)
  2006.       return false;
  2007.  
  2008.     var destination = this._request.destination;
  2009.  
  2010.     // Ensure that the file size matches the expected file size.
  2011.     if (destination.fileSize != this._patch.size)
  2012.       return false;
  2013.  
  2014.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  2015.         createInstance(nsIFileInputStream);
  2016.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2017.  
  2018.     try {
  2019.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  2020.           createInstance(nsICryptoHash);
  2021.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2022.       if (hashFunction == undefined)
  2023.         throw Components.results.NS_ERROR_UNEXPECTED;
  2024.       hash.init(hashFunction);
  2025.       hash.updateFromStream(fileStream, -1);
  2026.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2027.       // encoded binary (such as what is typically output by programs like
  2028.       // sha1sum).  In the future, this may change to base64 depending on how
  2029.       // we choose to compute these hashes.
  2030.       digest = binaryToHex(hash.finish(false));
  2031.     } catch (e) {
  2032.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  2033.       digest = "";
  2034.     }
  2035.  
  2036.     fileStream.close();
  2037.  
  2038.     return digest == this._patch.hashValue.toLowerCase();
  2039.   },
  2040.  
  2041.   /**
  2042.    * Select the patch to use given the current state of updateDir and the given
  2043.    * set of update patches.
  2044.    * @param   update
  2045.    *          A nsIUpdate object to select a patch from
  2046.    * @param   updateDir
  2047.    *          A nsIFile representing the update directory
  2048.    * @returns A nsIUpdatePatch object to download
  2049.    */
  2050.   _selectPatch: function(update, updateDir) {
  2051.     // Given an update to download, we will always try to download the patch
  2052.     // for a partial update over the patch for a full update.
  2053.  
  2054.     /**
  2055.      * Return the first UpdatePatch with the given type.
  2056.      * @param   type
  2057.      *          The type of the patch ("complete" or "partial")
  2058.      * @returns A nsIUpdatePatch object matching the type specified
  2059.      */
  2060.     function getPatchOfType(type) {
  2061.       for (var i = 0; i < update.patchCount; ++i) {
  2062.         var patch = update.getPatchAt(i);
  2063.         if (patch && patch.type == type)
  2064.           return patch;
  2065.       }
  2066.       return null;
  2067.     }
  2068.  
  2069.     // Look to see if any of the patches in the Update object has been
  2070.     // pre-selected for download, otherwise we must figure out which one
  2071.     // to select ourselves. 
  2072.     var selectedPatch = update.selectedPatch;
  2073.     
  2074.     var state = readStatusFile(updateDir)
  2075.  
  2076.     // If this is a patch that we know about, then select it.  If it is a patch
  2077.     // that we do not know about, then remove it and use our default logic.
  2078.     var useComplete = false;
  2079.     if (selectedPatch) {
  2080.       LOG("Downloader", "found existing patch [state="+state+"]");
  2081.       switch (state) {
  2082.       case STATE_DOWNLOADING: 
  2083.         LOG("Downloader", "resuming download");
  2084.         return selectedPatch;
  2085.       case STATE_PENDING:
  2086.         LOG("Downloader", "already downloaded and staged");
  2087.         return null;
  2088.       default:
  2089.         // Something went wrong when we tried to apply the previous patch.
  2090.         // Try the complete patch next time.
  2091.         if (update && selectedPatch.type == "partial") {
  2092.           useComplete = true;
  2093.         } else {
  2094.           // This is a pretty fatal error.  Just bail.
  2095.           LOG("Downloader", "failed to apply complete patch!");
  2096.           writeStatusFile(updateDir, STATE_NONE);
  2097.           return null;
  2098.         }
  2099.       }
  2100.  
  2101.       selectedPatch = null;
  2102.     }
  2103.     
  2104.     // If we were not able to discover an update from a previous download, we 
  2105.     // select the best patch from the given set.
  2106.     var partialPatch = getPatchOfType("partial");
  2107.     if (!useComplete)
  2108.       selectedPatch = partialPatch;
  2109.     if (!selectedPatch) {
  2110.       if (partialPatch)
  2111.         partialPatch.selected = false;
  2112.       selectedPatch = getPatchOfType("complete");
  2113.     }
  2114.  
  2115.     // Restore the updateDir since we may have deleted it.
  2116.     updateDir = getUpdatesDir();
  2117.     
  2118.     selectedPatch.selected = true;
  2119.     update.isCompleteUpdate = useComplete;
  2120.     
  2121.     // Reset the Active Update object on the Update Manager and flush the
  2122.     // Active Update DB. 
  2123.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2124.                        .getService(Components.interfaces.nsIUpdateManager);
  2125.     um.activeUpdate = update;
  2126.  
  2127.     return selectedPatch;
  2128.   },
  2129.  
  2130.   /**
  2131.    * Whether or not we are currently downloading something.
  2132.    */
  2133.   get isBusy() {
  2134.     return this._request != null;
  2135.   },
  2136.   
  2137.   /**
  2138.    * Download and stage the given update.
  2139.    * @param   update
  2140.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2141.    */
  2142.   downloadUpdate: function(update) {
  2143.     if (!update)
  2144.       throw Components.results.NS_ERROR_NULL_POINTER;
  2145.     
  2146.     var updateDir = getUpdatesDir();
  2147.  
  2148.     this._update = update;
  2149.  
  2150.     // This function may return null, which indicates that there are no patches
  2151.     // to download.
  2152.     this._patch = this._selectPatch(update, updateDir);
  2153.     if (!this._patch) {
  2154.       LOG("Downloader", "no patch to download");
  2155.       return readStatusFile(updateDir);
  2156.     }
  2157.     this.isCompleteUpdate = this._patch.type == "complete";
  2158.  
  2159.     var patchFile = updateDir.clone();
  2160.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2161.  
  2162.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2163.         getService(Components.interfaces.nsIIOService);
  2164.     var uri = ios.newURI(this._patch.URL, null, null);
  2165.  
  2166.     this._request =
  2167.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2168.         createInstance(nsIIncrementalDownload);
  2169.  
  2170.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " + 
  2171.         patchFile.path);
  2172.  
  2173.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2174.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2175.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2176.     this._request.start(this, null);
  2177.  
  2178.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2179.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2180.     this._patch.state = STATE_DOWNLOADING;
  2181.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2182.                        .getService(Components.interfaces.nsIUpdateManager);
  2183.     um.saveUpdates();
  2184.     return STATE_DOWNLOADING;
  2185.   },
  2186.   
  2187.   /**
  2188.    * An array of download listeners to notify when we receive 
  2189.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2190.    */
  2191.   _listeners: [],
  2192.  
  2193.   /** 
  2194.    * Adds a listener to the download process
  2195.    * @param   listener
  2196.    *          A download listener, implementing nsIRequestObserver and
  2197.    *          nsIProgressEventSink
  2198.    */
  2199.   addDownloadListener: function(listener) {
  2200.     for (var i = 0; i < this._listeners.length; ++i) {
  2201.       if (this._listeners[i] == listener)
  2202.         return;
  2203.     }
  2204.     this._listeners.push(listener);
  2205.   },
  2206.   
  2207.   /** 
  2208.    * Removes a download listener
  2209.    * @param   listener
  2210.    *          The listener to remove.
  2211.    */
  2212.   removeDownloadListener: function(listener) {
  2213.     for (var i = 0; i < this._listeners.length; ++i) {
  2214.       if (this._listeners[i] == listener) {
  2215.         this._listeners.splice(i, 1);
  2216.         return;
  2217.       }
  2218.     }
  2219.   },
  2220.   
  2221.   /**
  2222.    * When the async request begins
  2223.    * @param   request
  2224.    *          The nsIRequest object for the transfer
  2225.    * @param   context
  2226.    *          Additional data
  2227.    */
  2228.   onStartRequest: function(request, context) {
  2229.     request.QueryInterface(nsIIncrementalDownload);
  2230.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2231.     
  2232.     var listenerCount = this._listeners.length;
  2233.     for (var i = 0; i < listenerCount; ++i)
  2234.       this._listeners[i].onStartRequest(request, context);
  2235.   },
  2236.   
  2237.   /** 
  2238.    * When new data has been downloaded
  2239.    * @param   request
  2240.    *          The nsIRequest object for the transfer
  2241.    * @param   context
  2242.    *          Additional data
  2243.    * @param   progress
  2244.    *          The current number of bytes transferred
  2245.    * @param   maxProgress
  2246.    *          The total number of bytes that must be transferred
  2247.    */
  2248.   onProgress: function(request, context, progress, maxProgress) {
  2249.     request.QueryInterface(nsIIncrementalDownload);
  2250.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2251.     
  2252.     var listenerCount = this._listeners.length;
  2253.     for (var i = 0; i < listenerCount; ++i) {
  2254.       var listener = this._listeners[i];
  2255.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2256.         listener.onProgress(request, context, progress, maxProgress);
  2257.     }
  2258.   },
  2259.   
  2260.   /** 
  2261.    * When we have new status text
  2262.    * @param   request
  2263.    *          The nsIRequest object for the transfer
  2264.    * @param   context
  2265.    *          Additional data
  2266.    * @param   status
  2267.    *          A status code
  2268.    * @param   statusText
  2269.    *          Human readable version of |status|
  2270.    */
  2271.   onStatus: function(request, context, status, statusText) {
  2272.     request.QueryInterface(nsIIncrementalDownload);
  2273.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2274.     var listenerCount = this._listeners.length;
  2275.     for (var i = 0; i < listenerCount; ++i) {
  2276.       var listener = this._listeners[i];
  2277.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2278.         listener.onStatus(request, context, status, statusText);
  2279.     }
  2280.   },
  2281.   
  2282.   /** 
  2283.    * When data transfer ceases
  2284.    * @param   request
  2285.    *          The nsIRequest object for the transfer
  2286.    * @param   context
  2287.    *          Additional data
  2288.    * @param   status
  2289.    *          Status code containing the reason for the cessation.
  2290.    */
  2291.   onStopRequest: function(request, context, status) {
  2292.     request.QueryInterface(nsIIncrementalDownload);
  2293.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2294.  
  2295.     var state = this._patch.state;
  2296.     var shouldShowPrompt = false;
  2297.     var deleteActiveUpdate = false;
  2298.     const NS_BINDING_ABORTED = 0x804b0002;
  2299.     const NS_ERROR_ABORT = 0x80004004;
  2300.     if (Components.isSuccessCode(status)) {
  2301.       if (this._verifyDownload()) {
  2302.         state = STATE_PENDING;
  2303.         
  2304.         // We only need to explicitly show the prompt if this is a backround
  2305.         // download, since otherwise some kind of UI is already visible and 
  2306.         // that UI will notify. 
  2307.         if (this.background)
  2308.           shouldShowPrompt = true;
  2309.         
  2310.         // Tell the updater.exe we're ready to apply.
  2311.         writeStatusFile(getUpdatesDir(), state);
  2312.         this._update.installDate = (new Date()).getTime();
  2313.         this._update.statusText = "Install Pending";
  2314.       } else {
  2315.         LOG("Downloader", "onStopRequest: download verification failed");
  2316.         state = STATE_DOWNLOAD_FAILED;
  2317.         
  2318.         var sbs = 
  2319.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2320.             getService(Components.interfaces.nsIStringBundleService);
  2321.         var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2322.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2323.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2324.         this._update.statusText = updateStrings.
  2325.           formatStringFromName("verificationError", [brandShortName], 1);
  2326.         
  2327.         // TODO: use more informative error code here
  2328.         status = Components.results.NS_ERROR_UNEXPECTED;
  2329.         
  2330.         var message = getStatusTextFromCode("verification_failed", 
  2331.           "verification_failed");
  2332.         this._update.statusText = message;
  2333.         
  2334.         if (this._update.isCompleteUpdate)
  2335.           deleteActiveUpdate = true;
  2336.  
  2337.         // Destroy the updates directory, since we're done with it.
  2338.         cleanUpUpdatesDir();
  2339.       }
  2340.     }
  2341.     else if (status != NS_BINDING_ABORTED &&
  2342.              status != NS_ERROR_ABORT) {
  2343.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2344.       // Some sort of other failure, log this in the |statusText| property
  2345.       state = STATE_DOWNLOAD_FAILED;
  2346.       
  2347.       // XXXben - if |request| (The Incremental Download) provided a means
  2348.       // for accessing the http channel we could do more here.
  2349.       
  2350.       const NS_BINDING_FAILED = 2152398849;
  2351.       this._update.statusText = getStatusTextFromCode(status, 
  2352.         NS_BINDING_FAILED);
  2353.       
  2354.       // Destroy the updates directory, since we're done with it.
  2355.       cleanUpUpdatesDir();
  2356.       
  2357.       deleteActiveUpdate = true;
  2358.     }
  2359.     LOG("Downloader", "Setting state to: " + state);
  2360.     this._patch.state = state;
  2361.     var um = 
  2362.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2363.         getService(Components.interfaces.nsIUpdateManager);
  2364.     if (deleteActiveUpdate) {
  2365.       this._update.installDate = (new Date()).getTime();
  2366.       um.activeUpdate = null;
  2367.     }
  2368.     um.saveUpdates();
  2369.     
  2370.     var listenerCount = this._listeners.length;
  2371.     for (var i = 0; i < listenerCount; ++i)
  2372.       this._listeners[i].onStopRequest(request, context, status);
  2373.  
  2374.     this._request = null;
  2375.     
  2376.     if (state == STATE_DOWNLOAD_FAILED) {
  2377.       if (!this._update.isCompleteUpdate) {
  2378.         // If we were downloading a patch and the patch verification phase 
  2379.         // failed, log this and then commence downloading the complete update.
  2380.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2381.         this._update.isCompleteUpdate = true;
  2382.         var status = this.downloadUpdate(this._update);
  2383.         if (status == STATE_NONE)
  2384.           cleanupActiveUpdate();
  2385.         // This will reset the |.state| property on this._update if a new 
  2386.         // download initiates.
  2387.       }
  2388.       else {
  2389.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2390.         // ...
  2391.         
  2392.         // If this was ever a foreground download, and now there is no UI active
  2393.         // (e.g. because the user closed the download window) and there was an
  2394.         // error, we must notify now. Otherwise we can keep the failure to 
  2395.         // ourselves since the user won't be expecting it. 
  2396.         var fgdl = false;
  2397.         try {
  2398.           fgdl = this._update.getProperty("foregroundDownload");
  2399.         }
  2400.         catch (e) {
  2401.         }
  2402.         if (fgdl == "true") {
  2403.           var prompter = 
  2404.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2405.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2406.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2407.           this._update.setProperty("downloadFailed", "true");
  2408.           prompter.showUpdateError(this._update);
  2409.         }
  2410.       }
  2411.     }
  2412.  
  2413.     // Do this after *everything* else, since it will likely cause the app 
  2414.     // to shut down. 
  2415.     if (shouldShowPrompt) {
  2416.       // Notify the user that an update has been downloaded and is ready for 
  2417.       // installation (i.e. that they should restart the application). We do
  2418.       // not notify on failed update attempts.
  2419.       var prompter = 
  2420.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2421.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2422.       prompter.showUpdateDownloaded(this._update);
  2423.     }
  2424.   },
  2425.  
  2426.   /**
  2427.    * See nsIInterfaceRequestor.idl
  2428.    */
  2429.   getInterface: function(iid) {
  2430.     // The network request may require proxy authentication, so provide the
  2431.     // default nsIAuthPrompt if requested.
  2432.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2433.       var prompt =
  2434.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2435.           createInstance();
  2436.       return prompt.QueryInterface(iid);
  2437.     }
  2438.     Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  2439.     return null;
  2440.   },
  2441.    
  2442.   /**
  2443.    * See nsISupports.idl
  2444.    */
  2445.   QueryInterface: function(iid) {
  2446.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2447.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2448.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2449.         !iid.equals(Components.interfaces.nsISupports))
  2450.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2451.     return this;
  2452.   }
  2453. };
  2454.  
  2455. /**
  2456.  * A manager for update check timers. Manages timers that fire over long 
  2457.  * periods of time (e.g. days, weeks).
  2458.  * @constructor
  2459.  */
  2460. function TimerManager() {
  2461.   gOS = Components.classes["@mozilla.org/observer-service;1"]
  2462.                   .getService(Components.interfaces.nsIObserverService);
  2463.   gOS.addObserver(this, "xpcom-shutdown", false);
  2464.  
  2465.   const nsITimer = Components.interfaces.nsITimer;
  2466.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2467.                           .createInstance(nsITimer);
  2468.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2469.   this._timer.initWithCallback(this, timerInterval, 
  2470.                                nsITimer.TYPE_REPEATING_SLACK);
  2471. }
  2472. TimerManager.prototype = {
  2473.   /**
  2474.    * See nsIObserver.idl
  2475.    */
  2476.   observe: function(subject, topic, data) {
  2477.     if (topic == "xpcom-shutdown") {
  2478.       gOS.removeObserver(this, "xpcom-shutdown");
  2479.  
  2480.       // Release everything we hold onto. 
  2481.       this._timer = null;
  2482.       this._timers = null;
  2483.     }
  2484.   },
  2485.  
  2486.   /**
  2487.    * The Checker Timer
  2488.    */
  2489.   _timer: null,
  2490.   
  2491.   /**
  2492.    * The set of registered timers.
  2493.    */
  2494.   _timers: { },
  2495.   
  2496.   /**
  2497.    * Called when the checking timer fires.
  2498.    * @param   timer
  2499.    *          The checking timer that fired. 
  2500.    */
  2501.   notify: function(timer) {
  2502.     for (var timerID in this._timers) {
  2503.       var timerData = this._timers[timerID];
  2504.       var lastUpdateTime = timerData.lastUpdateTime;
  2505.       var now = Math.round(Date.now() / 1000);
  2506.     
  2507.       // Fudge the lastUpdateTime by some random increment of the update 
  2508.       // check interval (e.g. some random slice of 10 minutes) so that when
  2509.       // the time comes to check, we offset each client request by a random
  2510.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2511.       // whereas app.update.lastUpdateTime is in seconds
  2512.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2513.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2514.  
  2515.       if ((now - lastUpdateTime) > timerData.interval &&
  2516.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2517.         timerData.callback.notify(timer);
  2518.         timerData.lastUpdateTime = now;
  2519.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2520.         gPref.setIntPref(preference, now);
  2521.       }
  2522.     }
  2523.   },
  2524.   
  2525.   /**
  2526.    * See nsIUpdateService.idl
  2527.    */
  2528.   registerTimer: function(id, callback, interval) {
  2529.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2530.     var now = Math.round(Date.now() / 1000);
  2531.     var lastUpdateTime = null;
  2532.     if (gPref.prefHasUserValue(preference)) {
  2533.       lastUpdateTime = gPref.getIntPref(preference);
  2534.     } else {
  2535.       gPref.setIntPref(preference, now);
  2536.       lastUpdateTime = now;
  2537.     }
  2538.     this._timers[id] = { callback       : callback, 
  2539.                          interval       : interval,
  2540.                          lastUpdateTime : lastUpdateTime }; 
  2541.   },
  2542.  
  2543.   /**
  2544.    * See nsISupports.idl
  2545.    */
  2546.   QueryInterface: function(iid) {
  2547.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2548.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2549.         !iid.equals(Components.interfaces.nsIObserver) &&
  2550.         !iid.equals(Components.interfaces.nsISupports))
  2551.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2552.     return this;
  2553.   }
  2554. };
  2555.  
  2556. //@line 2525 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2557. /**
  2558.  * UpdatePrompt
  2559.  * An object which can prompt the user with information about updates, request
  2560.  * action, etc. Embedding clients can override this component with one that 
  2561.  * invokes a native front end. 
  2562.  * @constructor
  2563.  */
  2564. function UpdatePrompt() {
  2565. }
  2566. UpdatePrompt.prototype = {
  2567.   /**
  2568.    * See nsIUpdateService.idl
  2569.    */
  2570.   checkForUpdates: function() {
  2571.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2572.                  null, null);
  2573.   },
  2574.     
  2575.   /**
  2576.    * See nsIUpdateService.idl
  2577.    */
  2578.   showUpdateAvailable: function(update) {
  2579.     if (this._enabled) {
  2580.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2581.                    "updatesavailable", update);
  2582.     }
  2583.   },
  2584.   
  2585.   /**
  2586.    * See nsIUpdateService.idl
  2587.    */
  2588.   showUpdateDownloaded: function(update) {
  2589.     if (this._enabled) {
  2590.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2591.                    "finishedBackground", update);
  2592.     }
  2593.   },
  2594.   
  2595.   /**
  2596.    * See nsIUpdateService.idl
  2597.    */
  2598.   showUpdateInstalled: function(update) {
  2599.     var showUpdateInstalledUI = getPref("getBoolPref", 
  2600.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2601.     if (this._enabled && showUpdateInstalledUI) {
  2602.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2603.                    "installed", update);
  2604.     }
  2605.   },
  2606.   
  2607.   /**
  2608.    * See nsIUpdateService.idl
  2609.    */
  2610.   showUpdateError: function(update) {
  2611.     if (this._enabled) {
  2612.       // In some cases, we want to just show a simple alert dialog:
  2613.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2614.         var sbs = 
  2615.             Components.classes["@mozilla.org/intl/stringbundle;1"].
  2616.             getService(Components.interfaces.nsIStringBundleService);
  2617.         var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2618.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2619.         var text = updateBundle.formatStringFromName("updaterIOErrorText",
  2620.                                                      [gApp.name], 1);
  2621.         var ww =
  2622.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2623.             getService(Components.interfaces.nsIWindowWatcher);
  2624.         ww.getNewPrompter(null).alert(title, text);
  2625.       } else {
  2626.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard", 
  2627.                      "errors", update);
  2628.       }
  2629.     }
  2630.   },
  2631.   
  2632.   /**
  2633.    * See nsIUpdateService.idl
  2634.    */
  2635.   showUpdateHistory: function(parent) {
  2636.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History", 
  2637.                  null, null);
  2638.   },
  2639.   
  2640.   /**
  2641.    * Whether or not we are enabled (i.e. not in Silent mode)
  2642.    */
  2643.   get _enabled() {
  2644.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2645.   },
  2646.   
  2647.   /**
  2648.    * Show the Update Checking UI
  2649.    * @param   parent
  2650.    *          A parent window, can be null
  2651.    * @param   uri
  2652.    *          The URI string of the dialog to show
  2653.    * @param   name
  2654.    *          The Window Name of the dialog to show, in case it is already open
  2655.    *          and can merely be focused
  2656.    * @param   page
  2657.    *          The page of the wizard to be displayed, if one is already open.
  2658.    * @param   update
  2659.    *          An update to pass to the UI in the window arguments. 
  2660.    *          Can be null
  2661.    */
  2662.   _showUI: function(parent, uri, features, name, page, update) {
  2663.     var ary = null;
  2664.     if (update) {
  2665.       ary = Components.classes["@mozilla.org/supports-array;1"]
  2666.                       .createInstance(Components.interfaces.nsISupportsArray);
  2667.       ary.AppendElement(update);
  2668.     }
  2669.       
  2670.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  2671.                        .getService(Components.interfaces.nsIWindowMediator);
  2672.     var win = wm.getMostRecentWindow(name);
  2673.     if (win) {
  2674.       if (page && "setCurrentPage" in win)
  2675.         win.setCurrentPage(page);
  2676.       win.focus();
  2677.     }
  2678.     else {
  2679.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  2680.       if (features)
  2681.         openFeatures += "," + features;
  2682.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  2683.                          .getService(Components.interfaces.nsIWindowWatcher);
  2684.       ww.openWindow(parent, uri, "", openFeatures, ary);
  2685.     }
  2686.   },
  2687.   
  2688.   /**
  2689.    * See nsISupports.idl
  2690.    */
  2691.   QueryInterface: function(iid) {
  2692.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  2693.         !iid.equals(Components.interfaces.nsISupports))
  2694.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2695.     return this;
  2696.   }
  2697. };
  2698. //@line 2667 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2699.  
  2700. var gModule = {
  2701.   registerSelf: function(componentManager, fileSpec, location, type) {
  2702.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  2703.     
  2704.     for (var key in this._objects) {
  2705.       var obj = this._objects[key];
  2706.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  2707.                                                fileSpec, location, type);
  2708.     }
  2709.  
  2710.     // Make the Update Service a startup observer
  2711.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  2712.                                     .getService(Components.interfaces.nsICategoryManager);
  2713.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  2714.                                      "service," + this._objects.service.contractID, 
  2715.                                      true, true, null);
  2716.   },
  2717.   
  2718.   getClassObject: function(componentManager, cid, iid) {
  2719.     if (!iid.equals(Components.interfaces.nsIFactory))
  2720.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  2721.  
  2722.     for (var key in this._objects) {
  2723.       if (cid.equals(this._objects[key].CID))
  2724.         return this._objects[key].factory;
  2725.     }
  2726.     
  2727.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2728.   },
  2729.   
  2730.   _makeFactory: #1= function(ctor) {
  2731.     function ci(outer, iid) {
  2732.       if (outer != null)
  2733.         throw Components.results.NS_ERROR_NO_AGGREGATION;
  2734.       return (new ctor()).QueryInterface(iid);
  2735.     } 
  2736.     return { createInstance: ci };
  2737.   },
  2738.   
  2739.   _objects: {
  2740.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  2741.                contractID : "@mozilla.org/updates/update-service;1",
  2742.                className  : "Update Service",
  2743.                factory    : #1#(UpdateService)
  2744.              },
  2745.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  2746.                contractID : "@mozilla.org/updates/update-checker;1",
  2747.                className  : "Update Checker",
  2748.                factory    : #1#(Checker)
  2749.              },
  2750. //@line 2719 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2751.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  2752.                contractID : "@mozilla.org/updates/update-prompt;1",
  2753.                className  : "Update Prompt",
  2754.                factory    : #1#(UpdatePrompt)
  2755.              },
  2756. //@line 2725 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2757.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  2758.                contractID : "@mozilla.org/updates/timer-manager;1",
  2759.                className  : "Timer Manager",
  2760.                factory    : #1#(TimerManager)
  2761.              },
  2762.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  2763.                contractID : "@mozilla.org/updates/update-manager;1",
  2764.                className  : "Update Manager",
  2765.                factory    : #1#(UpdateManager)
  2766.              },
  2767.   },
  2768.   
  2769.   canUnload: function(componentManager) {
  2770.     return true;
  2771.   }
  2772. };
  2773.  
  2774. function NSGetModule(compMgr, fileSpec) {
  2775.   return gModule;
  2776. }
  2777.  
  2778. /**
  2779.  * Determines whether or there are installed addons which are incompatible 
  2780.  * with this update.
  2781.  * @param   update
  2782.  *          The update to check compatibility against
  2783.  * @returns true if there are no addons installed that are incompatible with
  2784.  *          the specified update, false otherwise.
  2785.  */
  2786. function isCompatible(update) {
  2787. //@line 2756 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2788.   var em = 
  2789.       Components.classes["@mozilla.org/extensions/manager;1"].
  2790.       getService(Components.interfaces.nsIExtensionManager);
  2791.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  2792.     nsIUpdateItem.TYPE_ADDON, false, { });
  2793.   return items.length == 0;
  2794. //@line 2765 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2795. }
  2796.  
  2797. /**
  2798.  * Shows a prompt for an update, provided there are no incompatible addons.
  2799.  * If there are, kick off an update check and see if updates are available
  2800.  * that will resolve the incompatibilities.
  2801.  * @param   update
  2802.  *          The available update to show
  2803.  */
  2804. function showPromptIfNoIncompatibilities(update) {
  2805.   function showPrompt(update) {
  2806.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  2807.     var prompter = 
  2808.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  2809.         createInstance(Components.interfaces.nsIUpdatePrompt);
  2810.     prompter.showUpdateAvailable(update);
  2811.   }
  2812.  
  2813. //@line 2784 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2814.   /**
  2815.    * Determines if an addon is compatible with a particular update.
  2816.    * @param   addon
  2817.    *          The addon to check
  2818.    * @param   version
  2819.    *          The extensionVersion of the update to check for compatibility 
  2820.    *          against.
  2821.    * @returns true if the addon is compatible, false otherwise
  2822.    */
  2823.   function addonIsCompatible(addon, version) {
  2824.     var vc = 
  2825.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  2826.         getService(Components.interfaces.nsIVersionComparator);
  2827.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  2828.           (vc.compare(version, addon.maxAppVersion) <= 0);
  2829.   }
  2830.  
  2831.   /**
  2832.    * An object implementing nsIAddonUpdateCheckListener that looks for 
  2833.    * available updates to addons and if updates are found that will make the 
  2834.    * user's installed addon set compatible with the update, suppresses the
  2835.    * prompt that would otherwise be shown.
  2836.    * @param   addons
  2837.    *          An array of incompatible addons that are installed.
  2838.    * @constructor
  2839.    */
  2840.   function Listener(addons) {
  2841.     this._addons = addons;
  2842.   }
  2843.   Listener.prototype = {
  2844.     _addons: null,
  2845.     
  2846.     /**
  2847.      * See nsIUpdateService.idl
  2848.      */
  2849.     onUpdateStarted: function() { 
  2850.     },
  2851.     onUpdateEnded: function() {
  2852.       // There are still incompatibilities, even after an extension update 
  2853.       // check to see if there were newer, compatible versions available, so
  2854.       // we have to prompt. 
  2855.       // 
  2856.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we 
  2857.       // handle incompatibilities:
  2858.       // 0    We count both VersionInfo updates _and_ NewerVersion updates
  2859.       //      against the list of incompatible addons installed - i.e. if
  2860.       //      Foo 1.2 is installed and it is incompatible with the update, and
  2861.       //      we find Foo 2.0 which is but which is not yet downloaded or 
  2862.       //      installed, then we do NOT prompt because the user can download
  2863.       //      Foo 2.0 when they restart after the update during the mismatch
  2864.       //      checking UI. This is the default, since it suppresses most 
  2865.       //      prompt dialogs. 
  2866.       // 1    We count only VersionInfo updates against the list of 
  2867.       //      incompatible addons installed - i.e. if the situation above
  2868.       //      with Foo 1.2 and available update to 2.0 applies, we DO show
  2869.       //      the prompt since a download operation will be required after
  2870.       //      the update. This is not the default and is supplied only as
  2871.       //      a hidden option for those that want it. 
  2872.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2873.                          INCOMPATIBLE_MODE_NEWVERSIONS);
  2874.       if ((mode == 0 && this._addons.length) || !isCompatible(update))
  2875.         showPrompt(update);
  2876.     },
  2877.     onAddonUpdateStarted: function(addon) {
  2878.     },
  2879.     onAddonUpdateEnded: function(addon, status) {
  2880.       if (status == Components.interfaces.nsIAddonUpdateCheckListener.STATUS_UPDATE &&
  2881.           addonIsCompatible(addon, update.extensionVersion)) {
  2882.         for (var i = 0; i < this._addons.length; ++i) {
  2883.           if (this._addons[i] == addon) {
  2884.             this._addons.splice(i, 1);
  2885.             break;
  2886.           }
  2887.         }
  2888.       }
  2889.     },
  2890.     /**
  2891.      * See nsISupports.idl
  2892.      */
  2893.     QueryInterface: function(iid) {
  2894.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  2895.           !iid.equals(Components.interfaces.nsISupports))
  2896.         throw Components.results.NS_ERROR_NO_INTERFACE;
  2897.       return this;
  2898.     }
  2899.   };
  2900.   
  2901.   if (!isCompatible(update)) {
  2902.     var em = 
  2903.         Components.classes["@mozilla.org/extensions/manager;1"].
  2904.         getService(Components.interfaces.nsIExtensionManager);
  2905.     var listener = new Listener(em.getIncompatibleItemList("", 
  2906.       update.extensionVersion, nsIUpdateItem.TYPE_ADDON, false, { }));
  2907.     // See documentation on |mode| above. 
  2908.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE, 
  2909.                        INCOMPATIBLE_MODE_NEWVERSIONS);
  2910.     em.update([], 0, mode != 0, listener);
  2911.   }
  2912.   else
  2913. //@line 2884 "/build/buildd/mozilla-thunderbird-1.5.0.10/build-dir/mozilla/toolkit/mozapps/update/src/nsUpdateService.js.in"
  2914.     showPrompt(update);
  2915. }
  2916.